<template>
  <div class="yd-form register">
    <figure class="logo">
			<img src="@/assets/logo.png">
      <h1>一点高人</h1>
		</figure>
		<group gutter="0">
			<x-input v-model="form.phone" placeholder="请输入手机号" required keyboard="number" ref="phone" @on-change="inputing" :icon-type="iconType" @on-blur="phoneValid" novalidate></x-input>
      <x-input v-model="form.code" placeholder="请输入验证码" required keyboard="number" ref="code" @on-change="inputing">
        <x-button slot="right" type="primary" plain mini @click.native="checkPhone" :disabled="start" class="vcode">
					<template v-if="start">
						<countdown v-model="time" :start="start" @on-finish="finishCode"></countdown>
						<span>s重新发送</span>
					</template>
					<span v-else>发送验证码</span>
				</x-button>
      </x-input>
		</group>

		<x-button type="primary" :disabled="!valid" @click.native="checkCode" class="btn-login">注册</x-button>

		<p class="agree f24">点击注册表示已同意<router-link to="/protocol">《一点高人使用协议》</router-link></p>
  </div>
</template>

<script>
import isMobilePhone from 'validator/lib/isMobilePhone';

export default {
  data() {
    return {
      iconType: '',
      form: {
        phone: "",
        code: "",
      },
      time: 60,
      start: false,
      valid: false,
    };
  },
  methods: {
    phoneValid() {
      if( isMobilePhone(this.form.phone, 'zh-CN') ){
        this.iconType = '';
      } else {
        this.iconType = 'error';
        this.$vux.toast.text('请输入正确的手机号');
      }
      return !this.iconType;
    },
    inputing() {
      this.valid = isMobilePhone(this.form.phone, 'zh-CN') && this.$refs.code.valid;
    },
    checkPhone() {
      if(!this.phoneValid()) return;
      
      this.$http.fetchGet("checkUserPhone", {
				phone: this.form.phone
			}).then(({ data = {} }) => {
				console.log("检查是否注册", data);
				if (data.status == 1) {
					this.$vux.toast.text("手机号已经存在<br/>请使用其他手机号");
					return setTimeout(() => {
						this.$refs.phone.focus();
					}, 2000);
				} else {
					this.sendCode();
				}
			});
    },
    sendCode() {
      this.$http.fetchGet("sendVerifyCode", {
				phone: this.form.phone
			}).then(({ data }) => {
				console.log("发送验证码", data);
				data && (this.start = true);
			});
    },
    finishCode() {
      this.start = false;
      this.time = 60;
    },
    checkCode() {
      this.$http.fetchGet("checkVerifyCode", {
				phone: this.form.phone,
				code: this.form.code
			}).then(({ data }) => {
        console.log("验证验证码", data);
        data && this.$router.push({
          path: '/register2',
          query: {
            phone: this.form.phone,
            code: this.form.code,
          }
        })
			});
    },
  }
};
</script>

<style scoped lang="less">
</style>
